﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SO.SharePoint.Utilities.Logging
{
    public class Logging
    {
        private static string ERR_CATEGORY = "DATALOG";

        // The following methods are used to write exepctions/information/warnings to the sharepoint log 
        private static void WriteToLog(TraceSeverity traceSeverity, EventSeverity eventSeverity, string msg)
        {
#if DEBUG
            System.Diagnostics.Debug.WriteLine(msg);
#endif

            SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
            string logEntry = String.Format("{0}", msg);

            diagSvc.WriteTrace(0, new SPDiagnosticsCategory(ERR_CATEGORY, traceSeverity, eventSeverity),
                traceSeverity,
                "Event: {0}",
                new object[] { logEntry });

            Console.WriteLine(msg);
        }

        public static void WriteException(string msg)
        {
            WriteToLog(TraceSeverity.Unexpected, EventSeverity.Error, msg);
        }

        public static void WriteException(Exception ex)
        {
            string exError = String.Empty;

            if (ex != null)
            {
                exError += ex.Message;
                if (String.IsNullOrEmpty(ex.StackTrace))
                    exError += String.Format(" - Stack Trace (Exeption): {0}", ex.StackTrace);

            }

            if (ex.InnerException != null)
            {
                exError += String.Format(" - Inner Exception: {0}", ex.InnerException.Message);
                if (String.IsNullOrEmpty(ex.InnerException.StackTrace))
                    exError += String.Format(" - Stack Trace (Inner Exception): {0}", ex.StackTrace);
            }


            WriteToLog(TraceSeverity.Unexpected, EventSeverity.Error, exError);
        }

        public static void WriteInformation(string msg)
        {
            WriteToLog(TraceSeverity.Monitorable, EventSeverity.Information, msg);
        }

        public static void WriteWarning(string msg)
        {
            WriteToLog(TraceSeverity.High, EventSeverity.Warning, msg);
        }
    }
}
